package com.frank.leftJoinQuery.specification;

import com.frank.leftJoinQuery.domain.StudentRequest;
import com.frank.leftJoinQuery.entity.Student;
import com.frank.leftJoinQuery.entity.Teacher;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 小石潭记
 * @date 2020/12/12 14:27
 * @Description: ${todo}
 */
@Component
public class Teacher1Specification {

    /**
     * root 就是mobile实例  root.get("name") name是属性名 不是数据库字段名
     * @param
     * @return
     * */
    public Specification<Teacher> getTeacherSpecification(StudentRequest request) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            // 主表老师的筛选生效的
            // 筛选教师名字
            if (StringUtils.isNotBlank(request.getName())) {
                Predicate teacherPre = criteriaBuilder.equal(root.get("name"), request.getName());
                predicateList.add(teacherPre);
            }
            // 筛选账户号
            if (StringUtils.isNotBlank(request.getAccountNumber())) {
                Predicate teacherPre = criteriaBuilder.equal(root.get("accountNumber"), request.getAccountNumber());
                predicateList.add(teacherPre);
            }
            // 使用左连接查询  注意这里的teacher不能乱起名字的
            Join<Teacher, Student> teacherJoin = root.join("studentList", JoinType.LEFT);
            // todo 关联表 学生表的筛选未生效
            if (StringUtils.isNotBlank(request.getAccountNumber())) {
                Predicate studentPre = criteriaBuilder.equal(teacherJoin.get("accountNumber"), request.getAccountNumber());
                predicateList.add(studentPre);
            }
            if (StringUtils.isNotBlank(request.getStudentName())) {
                Predicate studentPre = criteriaBuilder.equal(teacherJoin.get("name"), request.getStudentName());
                predicateList.add(studentPre);
            }
            if (StringUtils.isNotBlank(request.getGrade())) {
                Predicate studentPre = criteriaBuilder.equal(teacherJoin.get("grade"), request.getGrade());
                predicateList.add(studentPre);
            }
            criteriaQuery.distinct(true);
            return criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()])).getRestriction();
        };
    }

}
